<template>
  <div class="agent-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>代理列表</span>
          <div>
            <el-button type="success" @click="goToAgentTree"
              >代理结构</el-button
            >
            <el-button type="warning" @click="goToCommission"
              >佣金管理</el-button
            >
            <el-button type="primary" @click="handleAddAgent"
              >添加代理</el-button
            >
          </div>
        </div>
      </template>
      <div class="search-box">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="代理名称">
            <el-input
              v-model="queryParams.search"
              placeholder="名称/手机/邮箱"
              clearable
            />
          </el-form-item>
          <el-form-item label="代理等级">
            <el-select
              v-model="queryParams.level"
              placeholder="全部等级"
              clearable
            >
              <el-option :value="1" label="普通代理" />
              <el-option :value="2" label="高级代理" />
              <el-option :value="3" label="区域代理" />
              <el-option :value="4" label="总代理" />
            </el-select>
          </el-form-item>
          <el-form-item label="上级代理">
            <el-select
              v-model="queryParams.parent_id"
              placeholder="选择上级"
              clearable
            >
              <el-option value="null" label="顶级代理" />
              <el-option
                v-for="agent in parentOptions"
                :key="agent.id"
                :label="agent.name"
                :value="agent.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table v-loading="loading" :data="agentList">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="代理名称" />
        <el-table-column prop="level_name" label="代理等级">
          <template #default="scope">
            <el-tag :type="getLevelTagType(scope.row.level)">
              {{ scope.row.level_name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="parent_name" label="上级代理" />
        <el-table-column prop="mobile" label="手机号码">
          <template #default="scope">
            {{
              userStore.isTest ? maskMobile(scope.row.mobile) : scope.row.mobile
            }}
          </template>
        </el-table-column>
        <el-table-column prop="commission_rate" label="佣金比例">
          <template #default="scope">
            {{ (scope.row.commission_rate * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="账户余额">
          <template #default="scope">
            ¥{{ scope.row.balance.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status_text" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status_text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button size="small" plain @click="handleViewDetail(scope.row)"
              >详情</el-button
            >
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? "禁用" : "启用" }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.has_children"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="queryParams.page"
          :page-size="queryParams.per_page"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getAgentList, updateAgent, deleteAgent } from "@/api/agents";
import { useUserStore } from "@/store/user";

const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);
const agentList = ref([]);
const total = ref(0);
const parentOptions = ref([]);

const queryParams = reactive({
  page: 1,
  per_page: 10,
  search: "",
  level: "",
  parent_id: "",
});

// 获取代理列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getAgentList(queryParams);
    if (res.code === 0) {
      agentList.value = res.data.items || [];
      total.value = res.data.total || 0;

      // 更新上级代理选项列表
      if (parentOptions.value.length === 0) {
        // 提取所有代理作为上级代理选项
        parentOptions.value = agentList.value.map((item) => ({
          id: item.id,
          name: item.name,
        }));
      }
    } else {
      ElMessage.error(res.message || "获取代理列表失败");
    }
  } catch (error) {
    console.error("获取代理列表失败", error);
    ElMessage.error("获取代理列表失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleQuery = () => {
  queryParams.page = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryParams.search = "";
  queryParams.level = "";
  queryParams.parent_id = "";
  handleQuery();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.page = val;
  getList();
};

// 每页条数改变
const handleSizeChange = (val) => {
  queryParams.per_page = val;
  queryParams.page = 1;
  getList();
};

// 获取代理等级标签类型
const getLevelTagType = (level) => {
  const types = {
    1: "info", // 普通代理
    2: "success", // 高级代理
    3: "warning", // 区域代理
    4: "danger", // 总代理
  };
  return types[level] || "info";
};

// 手机号脱敏处理
const maskMobile = (mobile) => {
  if (!mobile) return "";
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
};

// 查看代理详情
const handleViewDetail = (row) => {
  router.push(`/agent/detail/${row.id}`);

  // const url = `${location.origin}/#/agent/detail/${row.id}`;
  // window.open(url, "_blank");
};

// 添加代理
const handleAddAgent = () => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能添加代理");
    return;
  }
  router.push("/agent/edit/0");
};

// 编辑代理
const handleEdit = (row) => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能编辑代理");
    return;
  }
  router.push(`/agent/edit/${row.id}`);
};

// 切换代理状态
const handleStatusChange = (row) => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能修改代理状态");
    return;
  }

  const statusText = row.status === 1 ? "禁用" : "启用";
  const newStatus = row.status === 1 ? 0 : 1;

  ElMessageBox.confirm(`确认要${statusText}该代理吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await updateAgent(row.id, { status: newStatus });
        if (res.code === 0) {
          ElMessage.success(`${statusText}成功`);
          getList();
        } else {
          ElMessage.error(res.message || `${statusText}失败`);
        }
      } catch (error) {
        console.error(`${statusText}失败`, error);
        ElMessage.error(`${statusText}失败`);
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 删除代理
const handleDelete = (row) => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能删除代理");
    return;
  }

  if (row.has_children) {
    ElMessage.warning("该代理有下级代理，不能删除");
    return;
  }

  ElMessageBox.confirm(
    `确认要删除代理"${row.name}"吗？此操作不可恢复！`,
    "警告",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    try {
      const res = await deleteAgent(row.id);
      if (res.code === 0) {
        ElMessage.success("删除成功");
        getList();
      } else {
        ElMessage.error(res.message || "删除失败");
      }
    } catch (error) {
      console.error("删除失败", error);
      ElMessage.error("删除失败");
    }
  });
};

// 前往代理树形结构页面
const goToAgentTree = () => {
  router.push("/agent/tree");
};

// 前往佣金管理页面
const goToCommission = () => {
  router.push("/agent/commission");
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.agent-list-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-box {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
